<template>
    <div class="userForm">
      <!-- element组件库的Dialog对话框默认可以通过点击 modal 关闭 Dialog，即点击空白处弹框可关闭。 -->
      <!-- :visible.sync 子组键改变父组件的值 控制子组件的显示-->
      <el-dialog title="新增用戶" :visible.sync="editDialogIsShow" :before-close="handleClose" :close-on-click-modal="false">
      <el-form :model="user" label-width="80px"  :rules="editUserRules" ref="editUserForm">
        <el-form-item label="姓名" prop="name">
          <el-col :span="16">
           <el-input v-model="user.name" placeholder="请填入姓名" clearable/>
          </el-col>
        </el-form-item>
        <el-form-item  label="性别">
          <el-col :span="16">
          <el-radio label="男" v-model="user.sex">男</el-radio><el-radio label="女" v-model="user.sex">女</el-radio>
          </el-col>
        </el-form-item>
        <el-form-item label="爱好">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="user.favs" @change="handleCheckedFavsChange">
              <el-checkbox v-for="fav in favs" :label="fav.num" :key="fav.num" :value="fav.num">{{fav.name}}</el-checkbox>
            </el-checkbox-group>
        </el-form-item>
        <el-form-item label="等级">
          <el-col :span="10">
            <el-select v-model="user.usergroup" placeholder="请选择">
              <el-option v-for="(usergroup,index) in allUserGroup" :key="usergroup.num" :label="usergroup.groupName" :value="usergroup.num"/>
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item label="邮件" prop="email">
          <el-col :span="16">
            <el-input v-model="user.email" placeholder="请填入邮件" @input="updateView($event)" clearable />
        </el-col>
        </el-form-item>

      </el-form>
      <el-row>
         <el-col :span="12">
         <span>&nbsp;</span></el-col>
        <el-col :span="6">
           <span><el-button type="primary" @click="editUser('editUserForm')">注册</el-button></span>
        </el-col>

    </el-row>
      </el-dialog>
    </div>
</template>

<script>
  import api from "../../../../axios/api"
  import rules from "../../../../static/js/validator/rules.js"
    const favOptions = [{num:0,name:'足球'}, {num:1,name:'篮球'}, {num:2,name:'游泳'}, {num:3,name:'跳舞'}];
    var initfavOption = [];
    export default {
        name: "editUser",
        data(){
          return {user:{name:"",sex:"",favs:[],usergroup:null,email:null},
              checkAll: false,
              //checkedFavs: ['唱歌', '游泳'],
              favs: favOptions,
              isIndeterminate: true,
              allUserGroup:[{num:0,"groupName":"初级会员"},{num:1,"groupName":"中级会员"},{num:2,"groupName":"高级会员"}],
              editUserRules:{name:[{required:true,message:"姓名不能为空",trigger:'blur'},{trigger:'blur',validator:this.validateName},
                  {max:20,min:2,message:'长度异常 长度在2-20之间',trigger:'blur'},{pattern:/^[\u0391-\uFFE5A-Za-z]+$/,message:'姓名必须为中文',trigger:'blur'}],
              email:[{required:true,message:"邮件不能为空",trigger:'blur'},{trigger:'change',validator:rules.FormValidate.Form().validateEmail}]},
              editDialogIsShow:false

          }
        },
      methods: {
         validateName:function(rule,value,callback){
           console.log(rule);
           if(value==1) {
              callback(new Error("1不正常"));
           }else{
             callback();
           }
  },
        init(user) {
          this.editDialogIsShow = true;
          this.user = user;
          console.log(user);
        },
        handleCheckAllChange(val) {
          this.user.favs = val ? initfavOption : [];
          this.isIndeterminate = false;
        },
        handleCheckedFavsChange(value) {
          let checkedCount = value.length;
          this.checkAll = checkedCount === this.favs.length;
          this.isIndeterminate = checkedCount > 0 && checkedCount < this.favs.length;
        },
        //关闭页面
        handleClose() {
          this.editDialogIsShow = false;
          //给父组件传参
          this.$emit("editDialogIsShow", this.editDialogIsShow);
        },
        editUser:function(editUserForm){
          this.$refs[editUserForm].validate(valid => {//此处refs对象和标签上的ref对应
            if (valid) {
              //如果通过验证 to do...
              console.log(this.user);
              alert(this.user.name+"添加成功");
              this.handleClose();
            } else {
              console.log('error submit!!')
              return false
            }
          });

        },
        //关闭页面
        handleClose() {
          this.editDialogIsShow = false;
          //给父组件传参
          this.$emit("editDialogIsShow", this.editDialogIsShow);
        },
        setDataFromAxios:function(){
          //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
          api.setDataFromAxios("/user/edit",this.user,"post")
            .then(res=>{this.leagues = res.leagues});//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        },
        updateView(e) {
          this.$forceUpdate();
        }

      },
      //监听
      watch: {
        editDialogIsShow(newValue, oldValue) {//配合:visible.sync监听变化
          this.editDialogIsShow = newValue;
        }
      },
      created() {
        for(var favindex=0;favindex < favOptions.length;favindex++){
          initfavOption.push(favOptions[favindex].name);
        }
      }
    }
</script>
<style scoped lang="stylus">
 .userForm
   margin 0 auto
   width 1000px
   text-align left
</style>
